const db = require('@root/db')

module.exports = {
  //获取文章分类列表
  getArticleCate(req, res) {
    db.query(
      `select * from article_cate where user_id=? and is_delete=0 order by id asc`,
      [req.auth.id],
      (err, resList) => {
        if (err) {
          res.ms(err)
        } else {
          res.ms('ok', 0, resList)
        }
      }
    )
  },
  //新增文章分类
  addArticleCate(req, res) {
    //查询名称,别名是否被占用
    db.query(
      `select * from article_cate where name =? or alias =?`,
      [req.body.name, req.body.alias],
      (err, resList) => {
        if (err) {
          res.ms(err)
        } else if (resList.length == 2) {
          res.ms('分类名称与别名已存在')
        } else if (resList.length == 1 && resList[0].name == req.body.name) {
          res.ms('分类名称已存在')
        } else if (resList.length == 1 && resList[0].alias == req.body.alias) {
          res.ms('分类别名已存在')
        } else {
          //添加到数据库
          req.body.user_id = req.auth.id
          db.query(`insert into article_cate set ?`, req.body, (err, dbRes) => {
            if (err) {
              res.ms(err)
            } else {
              res.ms('ok', 0)
            }
          })
        }
      }
    )
  },
  //根据id删除文章分类
  delArtCateById(req, res) {
    db.query(
      `update article_cate set is_delete=1 where Id=? and user_id =?`,
      [req.params.id, req.auth.id],
      (err, dbRes) => {
        if (err) {
          res.ms(err)
        } else if (dbRes.affectedRows != 1) {
          res.ms('删除失败')
        } else {
          res.ms('ok', 0)
        }
      }
    )
  },
  //根据id获取文章分类信息
  getArtCateInfo(req, res) {
    db.query(
      `select * from article_cate where Id=? and user_id=?`,
      [req.params.id, req.auth.id],
      (err, resList) => {
        if (err) {
          res.ms(err)
        } else {
          res.ms('ok', 0, resList)
        }
      }
    )
  },

  //更新文章分类信息
  updateCateInfo(req, res) {
    const data = req.body
    db.query(
      `update article_cate set name=?,alias=? where Id=? and user_id=?`,
      [data.name, data.alias, data.Id, req.auth.id],
      (err, dbRes) => {
        if (err) {
          res.ms(err)
        } else if (dbRes.affectedRows != 1) {
          res.ms('更新失败')
        } else {
          res.ms('ok', 0)
        }
      }
    )
  }
}
